package com.nwpu.coursesupport.realm;

import java.util.Collection;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.nwpu.coursesupport.entity.Student;
import com.nwpu.coursesupport.entity.bean.Setting;
import com.nwpu.coursesupport.service.imple.StudentService;

public class StudentAuthorizingRealm extends AuthorizingRealm {
	
    private static Logger logger = LoggerFactory.getLogger(StudentAuthorizingRealm.class);
	
	@Autowired
	private StudentService studentService;
	@Autowired
	private Setting setting;
	
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { 
		Collection list=principals.fromRealm(this.getName());
		if(list==null||list.size()<=0){
			return null;
		}
		SimpleAuthorizationInfo simpleAuthorInfo = new SimpleAuthorizationInfo(); 
	     simpleAuthorInfo.addRole("student"); 
	     return simpleAuthorInfo;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
		try{
			CustomizedToken token = (CustomizedToken)authcToken;  
			logger.debug(token.getUsername()+"登录");
			Student student = studentService.findByStudentCode(token.getUsername());  
	        if(student == null){
	        	return null;
	        }
	        token.setId(student.getId());
	        token.setName(student.getName());
	        token.setImage(student.getPicture());
	        ByteSource credentialsSalt = ByteSource.Util.bytes(student.getStudentCode());
	        AuthenticationInfo authcInfo = new SimpleAuthenticationInfo(student.getStudentCode(),student.getPassword(),credentialsSalt, this.getName());  
	        
	        return authcInfo;  
		}catch(Exception e){
			logger.error("学生登录出现问题："+e.getMessage());
		}
		return null;
       
	}

}
